package com.xhb.biz.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.solon.service.impl.ServiceImpl;
import com.xhb.biz.constant.UserConfigConstant;
import com.xhb.biz.feign.UserCollectUploadService;
import com.xhb.biz.feign.UserDataSyncService;
import com.xhb.biz.mapper.CollectGroupMapper;
import com.xhb.biz.po.CollectGroupPO;
import com.xhb.biz.po.ConfigPO;
import feign.Feign;
import feign.Request;
import feign.Retryer;
import feign.jackson.JacksonEncoder;
import org.noear.solon.Solon;
import org.noear.solon.annotation.Inject;
import org.noear.solon.aspect.annotation.Service;
import org.noear.solon.data.annotation.Tran;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * (t_collect_group)}表服务接口
 *
 * @author tanyukun
 * @since 2023-02-06 13:44:04
 */
@Service
public class CollectGroupService extends ServiceImpl<CollectGroupMapper, CollectGroupPO> {

    @Inject("${manager.url}")
    String managerServerUrl;


    UserCollectUploadService userCollectUploadService;

    /**
     * 首页导航分组同步
     *
     * @param userService feign 接口
     * @param headers     请求头
     */
    @Tran
    public void userCollectGroup(UserDataSyncService userService, Map<String, Object> headers) {
        String data = userService.getUserCollectGroupList(headers);
        List<CollectGroupPO> userCollGroupPos = JSONUtil.toList(data, CollectGroupPO.class);
        if (CollectionUtil.isNotEmpty(userCollGroupPos)) {
            super.saveOrUpdateBatch(userCollGroupPos);
        }
    }

    /**
     * 异步插入
     *
     * @param name
     */
    @Tran
    public void insert(String name) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.select("IFNULL( max(sort_no),0) as sortNo");
        CollectGroupPO maxSortNoPo = this.getOne(wrapper);

        CollectGroupPO addPo = CollectGroupPO.builder()
                .sortNo(maxSortNoPo.getSortNo() + 1)
                .name(name)
                .build();
        // 先调服务端接口获取新增数据的主键
        ConfigService configService = Solon.context().getBean(ConfigService.class);
        ConfigPO configPo = configService.selectUserConfigByKey(UserConfigConstant.USER_TOKEN_KEY);
        if (null != configPo) {
            String params = JSONUtil.toJsonStr(addPo);
            String result = getUserTokenService().addUserCollectGroup(getHeaders(), params);
            JSONObject resultJson = JSONUtil.parseObj(result);
            addPo.setId(resultJson.getStr("data"));
        }
        super.save(addPo);
    }

    @Tran
    public void update(CollectGroupPO po) {
        // 先调服务端接口
        ConfigService configService = Solon.context().getBean(ConfigService.class);
        ConfigPO configPo = configService.selectUserConfigByKey(UserConfigConstant.USER_TOKEN_KEY);
        if (null != configPo) {
            String params = JSONUtil.toJsonStr(po);
            getUserTokenService().updateUserCollectGroup(getHeaders(), params);
        }
        super.updateById(po);
    }

    @Tran
    public void delete(String collectGroupId) {
        // 先调服务端接口
        ConfigService configService = Solon.context().getBean(ConfigService.class);
        ConfigPO configPo = configService.selectUserConfigByKey(UserConfigConstant.USER_TOKEN_KEY);
        if (null != configPo) {
            getUserTokenService().delUserCollectGroup(getHeaders(), collectGroupId);
        }
        super.removeById(collectGroupId);
    }


    public UserCollectUploadService getUserTokenService() {
        if (null == userCollectUploadService) {
            userCollectUploadService = Feign.builder()
                    .encoder(new JacksonEncoder())
                    .options(new Request.Options(1000, 3500))
                    .retryer(new Retryer.Default(5000, 5000, 3))
                    .target(UserCollectUploadService.class, managerServerUrl);
        }
        return userCollectUploadService;
    }

    public Map<String, Object> getHeaders() {
        ConfigService configService = Solon.context().getBean(ConfigService.class);
        ConfigPO configPo = configService.selectUserConfigByKey(UserConfigConstant.USER_TOKEN_KEY);
        if (null == configPo) {
            return null;
        }
        Map<String, Object> headers = new HashMap<>(2);
        headers.put(UserConfigConstant.USER_TOKEN_KEY, configPo.getContent());
        headers.put("Content-Type", "application/json");
        return headers;
    }

}
